package engine.sound;

import java.nio.FloatBuffer;

import org.lwjgl.BufferUtils;
import org.lwjgl.openal.AL10;

public class Sound {
	
	private float pitch = 1.0f;
	private float gain = 1.0f;
	private float volume = 1.0f;
	
	private FloatBuffer position = BufferUtils.createFloatBuffer(3).put(new float[]{0, 0, 0});
	private FloatBuffer velocity = BufferUtils.createFloatBuffer(3).put(new float[]{1, 1, 1});
	private boolean loop = false;
	
	public Sound(String path) {
		id = SoundManager.loadALSample(path);
		
		AL10.alSourcef(id, AL10.AL_PITCH, pitch);
		AL10.alSourcef(id, AL10.AL_GAIN, gain);
		AL10.alSourcei(id, AL10.AL_LOOPING, loop ? AL10.AL_TRUE : AL10.AL_FALSE);

		position.flip();
		velocity.flip();

		AL10.alSource(id, AL10.AL_POSITION, position);
		AL10.alSource(id, AL10.AL_VELOCITY, velocity);
	}
	
	private int id;

	public int getId() {
		return id;
	}
	
	public void setId(int id) {
		this.id = id;
	}
	
	/**
	 * Set the sound volume
	 * 
	 * @param volume
	 *            The volume for sound fx
	 */
	public void setVolume(float volume) {
		this.volume = volume;
		
		AL10.alSourcef(id, AL10.AL_GAIN, volume);
	}
	
	public float getVolume() {
		return volume;
	}

	public void setLoop(boolean loop) {
		this.loop = loop;
		
		AL10.alSourcef(id, AL10.AL_LOOPING, loop ? AL10.AL_TRUE : AL10.AL_FALSE);
	}
	
	public boolean getLoop() {
		return loop;
	}
	
	/**
	 * Set the pitch at which the current music is being played
	 * 
	 * @param pitch
	 *            The pitch at which the current music is being played
	 */
	public void setPitch(float pitch) {
		this.pitch = pitch;
		
		AL10.alSourcef(id, AL10.AL_PITCH, pitch);
	}
	
	public float getPitch() {
		return pitch;
	}

	public void setGain(float gain) {
		this.gain = gain;
		
		AL10.alSourcef(id, AL10.AL_GAIN, gain);
	}
	
	public float getGain() {
		return gain;
	}
	
	public void setPosition(float[] pos) {
		position = BufferUtils.createFloatBuffer(3).put(pos);
		position.flip();

		AL10.alSource(id, AL10.AL_POSITION, position);
	}
	
	public FloatBuffer getPosition() {
		return position;
	}
	
	public void setVelocity(float[] vel) {
		velocity = BufferUtils.createFloatBuffer(3).put(vel);
		velocity.flip();

		AL10.alSource(id, AL10.AL_VELOCITY, velocity);
	}

	public FloatBuffer getVelocity() {
		return velocity;
	}
	
	public void play() {
		AL10.alSourcePlay(id);
	}

	public void stop() {
		AL10.alSourceStop(id);
	}

	public void pause() {
		AL10.alSourcePause(id);
	}

	public boolean isPlaying() {
		int state = AL10.alGetSourcei(id, AL10.AL_SOURCE_STATE);

		if(state == AL10.AL_PLAYING) {
			return true;
		}

		return false;
	}
}
